package order;


import activity.give.GiveActivitySpecProduct;
import address.Address;
import build.OrderBuilder;
import coupon.DiscountCoupon;
import coupon.WebUserCoupon;
import coupon.WebUserCouponHistory;
import enums.*;
import jodd.util.StringUtil;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import models.weixin.amount.WebUserAccount;
import models.weixin.amount.WebUserAccountHistory;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;
import product.enums.ProductAttribute;
import product.merchant.ProductSpecMerchant;
import util.common.ConvertUtil;

import javax.persistence.*;
import java.util.*;

/**
 * Created by upshan on 15/7/7.
 */
@Entity
@Table(name = "orders")
public class Order extends BaseModel {


    /**
     * 订单来源
     */
    @JoinColumn(name = "order_source_id", nullable = true)
    @ManyToOne
    public OrderSource orderSource;

    /**
     * 下单用户
     */
    @JoinColumn(name = "web_user_id", nullable = true)
    @ManyToOne
    public WebUser webUser;



    /**
     * 所属商户
     */
    @JoinColumn(name = "fee_merchant_id", nullable = true)
    @ManyToOne
    public Merchant merchant;

    /**
     * 状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "timing_status")
    public TimingStatus timingStatus;

    /**
     * 配送地址
     */
    @JoinColumn(name = "address_id", nullable = true)
    @ManyToOne
    public Address address;


    /**
     * 订单名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 防止后退刷新一直添加订单
     */
    @Column(name = "uuid")
    public String uuid;


    /**
     * 订单号
     */
    @Column(name = "order_no")
    public String orderNumber;

    /**
     * 第三方平台订单号
     */
    @Column(name = "third_party_number")
    public String thirdPartyNumber;


    /**
     * 订单总金额
     */
    @Column(name = "amount")
    public Double amount= 0D;

    /**
     * 订单折扣金额  比如活动折扣 使用优惠券金额  赠送金额
     */
    @Column(name = "discount_pay")
    public Double discountPay= 0D;

    /**
     * 已支付金额 实际支付金额
     */
    @Column(name = "paymented_amount")
    public Double paymentedAmount= 0D;


    /**
     * 合伙人金额
     */
    @Column(name = "partner_amount")
    public Double partnerAmount= 0D;


    /**
     * 支付的运费
     */
    @Column(name = "freight")
    public Double freight = 0D;

    /**
     * 已退款金额
     */
    @Column(name = "refunded_amount")
    public Double refundedAmount= 0D;

    /**
    * 订单支付状态
    */
    @Enumerated(EnumType.STRING)
    @Column(name = "status")
    public OrderStatus status;

    /**
    * 订单支付状态
    */
    @Transient
    public String orderStatusStr;


    /**
    * 订单类型
    */
    @Enumerated(EnumType.STRING)
    @Column(name = "goods_type")
    public GoodsType goodsType;

    /*
    * 订单类型
    */
    @Transient
    public String goodsTypeStr;


    /**
     * 订单类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "order_type")
    public OrderType type;


    /**
     * 支付类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "payment_type")
    public PaymentType paymentType;



    /**
     * 订单备注信息
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 付款时间
     */
    @Column(name = "payed_at")
    public Date payedAt;

    /**
     * 创建时间
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 创建时间
     */
    @Transient
    public String createdAtStr;

    /**
     * 确认状态
     */
    @Column(name = "confirm_status")
    public String confirmStatus;



    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;



    /**
     * 订单派发状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "distribute_status")
    public DistributeStatus distributeStatus = DistributeStatus.UN_DISTRIBUTE;

    /**
     * 订单派发状态
     */
    @Transient
    public String distributeStatusStr;


    /**
     * 派单时间
     */
    @Column(name = "distribute_at")
    public Date distributeAt;

    /**
     * 派单时间
     */
    @Transient
    public String distributeAtStr;

    /**
     * 抢单时间
     */
    @Column(name = "rob_distribute_at")
    public Date robDistributeAt;

    /**
     * 配送员送到时间
     */
    @Column(name = "sent_at")
    public Date sentAt;

    /**
     * 用户确认收货时间
     */
    @Column(name = "web_user_sent_at")
    public Date webUserSentAt;


    /**
     * 抢单人
     */
    @JoinColumn(name = "distribute_web_user_id", nullable = true)
    @ManyToOne
    public WebUser distributeWebUser;




//    @OneToMany(fetch = FetchType.LAZY, mappedBy = "order")
//    @OrderBy("id")
    @Transient
    public List<Map<String, Object>> orderItemsMap;

    @Transient
    public String sts;

    //自定义字段
    @Transient
    public String defineStr;

    @Transient
    public List<OrderItem> orderItems;

    // 品类数
    public Integer kindNumber;

    public String proName = "";

    public String roomId;

    @Transient
    public String sumAmount;


    /**
     * 订单打印包装订单明细使用
     */
    @Transient
    public List<Map<String,Object>> orderItemList;

    /**
     * 为了解决订单明细超过 12 的情况将订单明细转化后放入到此对象中
     */
    @Transient
    public List<List<Map<String, Object>>> orderItemPages;


    /**
     * 分页查询.
     *
     * if(StringUtil.isNotBlank(startTime)) {
     searchMap.put("startTime", startTime);
     }

     if(StringUtil.isNotBlank(endTime)) {
     searchMap.put("endTime", endTime);
     }

     if(StringUtil.isNotBlank(status)) {
     searchMap.put("status", status);
     }

     if(StringUtil.isNotBlank(payType)) {
     searchMap.put("payType", payType);
     }

     if(StringUtil.isNotBlank(orderType)) {
     searchMap.put("orderType", orderType);
     }
     */
    public static JPAExtPaginator<Order> findByCondition(Map<String, Object> conditionMap, String orderByExpress, Integer pageNumber, Integer pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED  ")
            /*  .append(" and t.distributeStatus = enums.DistributeStatus.UN_DISTRIBUTE")*/
                .append("/~ and t.orderNumber = {orderNumber} ~/")
                .append("/~ and t.merchant.id = {merchantId} ~/")
                .append("/~ and t.createdAt >= STR_TO_DATE({startTime},'%Y-%m-%d %H:%i:%s') ~/")
                .append("/~ and t.createdAt <= STR_TO_DATE({endTime},'%Y-%m-%d %H:%i:%s') ~/")
                .append("/~ and t.status = {status} ~/")
                .append("/~ and t.paymentType = {payType} ~/")
                .append("/~ and t.goodsType = {orderType} ~/")
                .append("/~ and (t.goodsType = {orderType0} or t.goodsType = {orderType1} or t.goodsType = {orderType2}) ~/");


        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        Logger.info("sql : %s" , result.getXsql());
        JPAExtPaginator<Order> orderPage = new JPAExtPaginator<>("Order t", "t", Order.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        if(pageNumber != null && pageSize != null) {
            orderPage.setPageNumber(pageNumber);
            orderPage.setPageSize(pageSize);
        }
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }

    public static Order findByOrderNumber(String orderNumber) {
        return find("orderNumber = ?1 and deleted = ?2", orderNumber , DeletedStatus.UN_DELETED).first();
    }

    /**
     * 根据订单状态查询订单. 将来肯定需要 增加分页功能
     * @param status
     * @return
     */
    public static List<Order> findByStatus(OrderStatus status,WebUser webUser) {
        if(status == null || "".equals(status) || "all".equals(status)){
            return find(" deleted = ?1 and webUser = ?2 order by createdAt desc",DeletedStatus.UN_DELETED,webUser).fetch();
        }else {
            return find("deleted = ?1 and status = ?2  and webUser = ?3 order by createdAt desc" , DeletedStatus.UN_DELETED , status,webUser).fetch();
        }
    }

    /**
     * 根据订单状态查询订单. 将来肯定需要 增加分页功能
     * @param status
     * @return
     */
    public static List<Order> findByStatusAndWebuserAndMerchant(OrderStatus status,WebUser webUser , Merchant merchant) {
        if(status == null || "".equals(status) || "all".equals(status)){
            return find(" deleted = ?1 and webUser = ?2 and merchant = ?3  order by createdAt desc",DeletedStatus.UN_DELETED,webUser , merchant).fetch();
        }else {
            return find("deleted = ?1 and status = ?2  and webUser = ?3 and merchant = ?4  order by createdAt desc" , DeletedStatus.UN_DELETED , status,webUser , merchant).fetch();
        }
    }

    /**
     * 查询未支付订单数
     * @return
     */
    public static List<Order> countPaidUnConfirm(long merchantId) {
        return find(" deleted = ?1 and status = ?2 and confirmStatus is null and merchant.id=?3 ", DeletedStatus.UN_DELETED, OrderStatus.PAID, merchantId).fetch();
    }

    /**
     * 查询开始计时中的包房订单
     * @return
     */
    public static List<Order> findTimingStartOrders(long merchantId, String phone) {
        if(phone != null && !"".equals(phone)){
            return find(" deleted = ?1 and goodsType = ?2 and timingStatus = ?3 and merchant.id=?4 and webUser.phone=?5 order by createdAt desc", DeletedStatus.UN_DELETED, GoodsType.SPORTS_ROOMS, TimingStatus.START, merchantId, phone).fetch();
        }else{
            return find(" deleted = ?1 and goodsType = ?2 and timingStatus = ?3 and merchant.id=?4 order by createdAt desc", DeletedStatus.UN_DELETED, GoodsType.SPORTS_ROOMS, TimingStatus.START, merchantId).fetch();
        }
    }

    /**
     * 根据订单状态查询订单. 将来肯定需要 增加分页功能
     * @param status
     * @return
     */
    public static Long countByStatus(OrderStatus status,WebUser webUser) {
        if(status == null || "".equals(status) ){
            return count(" deleted = ?1 and webUser = ?2",DeletedStatus.UN_DELETED,webUser);
        }else {
            return count("deleted = ?1 and status = ?2  and webUser = ?3 " , DeletedStatus.UN_DELETED , status,webUser);
        }
    }

    /**
     * 根据订单状态查询订单. 将来肯定需要 增加分页功能
     * @return
     */
    public static Long countByWebUser(WebUser webUser) {
            return count(" deleted = ?1 and webUser = ?2 and payedAt != null",DeletedStatus.UN_DELETED,webUser);
    }

    /**
     * 根据订单状态查询订单. 将来肯定需要 增加分页功能
     * @param status
     * @return
     */
    public static Long countByStatusAndWebuserAndMerchant(OrderStatus status,WebUser webUser ) {
        if(status == null || "".equals(status) ){
            return count(" deleted = ?1 and webUser = ?2 ",DeletedStatus.UN_DELETED,webUser );
        }else {
            return count("deleted = ?1 and status = ?2  and webUser = ?3 " , DeletedStatus.UN_DELETED , status,webUser );
        }
    }


    public static List<OrderItem> getOrderItems(Order order) {
        return OrderItem.findByOrder(order);
    }

    public static List<Order> findByStatusAndDate(OrderStatus status , Date beginAt , Date endAt) {
        return Order.find("deleted = ?1 and status = ?2 and createdAt between ?3 and ?4" , DeletedStatus.UN_DELETED , OrderStatus.UNPAID , beginAt , endAt).fetch();
    }

    public static void updateOrderPayStatus(Order order){

            // 修改订单状态
            order.remark = "订单支付异常  人工修改支付状态";
            order.save();
            OrderBuilder.orderNumber(order.orderNumber).changeToPaid();

            // 设置订单支付方式
            setPaymentType(PaymentType.WEIXIN_PUB , order);

            //Redis 更新数量  并且设置购物车
//            updateRedisProduct(order);

            // 如果是充值卡  则 金额充值到账户中
            checkToAccount(order);

            // 如果有代金券赠送政策  则赠送代金券
            DiscountCoupon.checkToCoupon(order);

            //用户消费成功 减少代金券
            checkReduceCoupon(order);

            //修改库存
            changeProductNumber(order);

            //检查是否有赠品
            checkGiveSpecProduct(order);

            Logger.info("订单号为: %s 的订单 支付状态修改成功" , order.orderNumber);


    }


    /**
     * 设置订单支付方式
     * @param payType
     * @param order
     */
    private static void setPaymentType(PaymentType payType , Order order) {
        if(payType != null) {
            order.paymentType = payType;
            order.save();
        }
    }

    /**
     *
     * @param order
     */
//    private static void updateRedisProduct(Order order) {
//        List<OrderItem> orderItems = OrderItem.getListByOrder(order);
//        List<ShopCart> shopCartList = ShopCart.findShopCartByUserAndMerchant(order.webUser, order.merchant.id);
//        for(OrderItem oi : orderItems) {
//            ProductSpecMerchant psm = OrderItem.getProductSpecMerchantByOrderItem(oi);
//            for(ShopCart shopCart : shopCartList) {
//                //修改购物车信息
//                if(oi.goods == shopCart.goods) {
//                    shopCart.status = ShopCartStatus.BUY;
//                    shopCart.deleted = DeletedStatus.DELETED;
//                    shopCart.save();
//                }
//            }
//            ProductSpecMerchant.subtractRedis(psm , oi.buyNumber);
//        }
//
//        //更新购物车缓存数量
//        Long shopcartCount = ShopCart.findShopCartSize(order.webUser,order.merchant.id);
//        CacheHelper.objectToCache(ShopCart.CACHE_SHOP_CART_COUNT + order.webUser.id + "_" + order.merchant.id , shopcartCount.toString());
//    }

    /**
     * 检测产品是否为  充值卡 。 如果为充值卡。 钱充值到 个人帐户中
     * @param order
     */
    private static void checkToAccount(Order order) {
        //查看个人微信账户
        WebUserAccount account = WebUserAccount.findByWebUser(order.webUser);
        // 如果微信账户为空 创建一个微信账户
        if(account == null) {
            account = new WebUserAccount(order.webUser , 0d).save();
        }
        // 查询订单商品类目
        List<OrderItem> orderItems = OrderItem.findByOrder(order);
        for(OrderItem orderItem : orderItems) {
            // 订单商品对应到 商户商品
            ProductSpecMerchant specMerchant = ProductSpecMerchant.findById(orderItem.goods.serialId);
            if(specMerchant != null && specMerchant.productSpec.product != null) {
                if(specMerchant.productSpec.product.type != null && specMerchant.productSpec.product.type == ProductAttribute.RECHARGEABLE_CARD) {
                    // 修改个人中心账户金额
                    account.amount +=  (specMerchant.productSpec.amount + specMerchant.productSpec.giveAmount);
                    account.save();
                    new WebUserAccountHistory(account , specMerchant.productSpec.amount , specMerchant.productSpec.giveAmount , "用户购买:" +specMerchant.productSpec.product.name + "。型号为:" + specMerchant.productSpec.unit).save();
                }
            }
        }
    }

    /**
     * 用户消费成功  减少代金券
     * @param order
     */
    private static void checkReduceCoupon(Order order) {
        WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(order.webUser);
        if(webUserCoupon != null && order.discountPay != null && order.discountPay > 0) {
            if(webUserCoupon.amount > order.discountPay) {
                new WebUserCouponHistory(webUserCoupon , "订单:" + order.orderNumber + "消费代金券" , order.discountPay * (-1)).save();
                webUserCoupon.amount = webUserCoupon.amount - order.discountPay;
                webUserCoupon.save();
            } else {
                new WebUserCouponHistory(webUserCoupon , "订单:" + order.orderNumber + "消费代金券 | 卡券金额小于订单折扣金额  卡券金额: " + webUserCoupon.amount + "订单折扣金额:" + order.discountPay , order.discountPay * (-1)).save();
                webUserCoupon.amount = 0d;
                webUserCoupon.save();
            }

        }
    }


    /**
     * 修改库存
     * @param order
     * @return
     */
    private static String changeProductNumber(Order order) {
        List<OrderItem> orderItems = OrderItem.getListByOrder(order);
        StringBuffer itemNames = new StringBuffer();
        for(OrderItem orderItem : orderItems) {
            itemNames.append("\n商品名称: " + orderItem.goods.name +  "  金额: " + orderItem.salePrice+ " 数量:" + orderItem.buyNumber+ ";");
            //更新商品库存数量
            ProductSpecMerchant psm = ProductSpecMerchant.findById(orderItem.goods.serialId);
            Logger.info("更新前库存:%s",psm.stock);
            psm.stock = psm.stock - orderItem.buyNumber;
            Logger.info("更新后库存:%s",psm.stock);
            psm.save();
        }
        return itemNames.toString();
    }

    /**
     * 添加赠品
     * @param order
     */
    private static void checkGiveSpecProduct(Order order) {
        Logger.info("Log 120003 Order : %s" , order);
        //判断是否有赠品
        if(order.merchant!=null && order.merchant.offeringFreebies != null &&  order.merchant.offeringFreebies ){
            Logger.info("Log 1200002  merchant  specMerchant : %s ", order.merchant);
            GiveActivitySpecProduct giveProduct = GiveActivitySpecProduct.getRandomProduct(order.amount,order.merchant.id);
            if(giveProduct != null && giveProduct.productSpecMerchant != null){
                ProductSpecMerchant specMerchant = giveProduct.productSpecMerchant ;
                Logger.info("Log 1200001  checkGiveSpecProduct  specMerchant : %s ", specMerchant.productSpec.product.name);
                // 加入 Order
                OrderItem orderItem = new  OrderItem(order,specMerchant, 0d , giveProduct.giveNum, OrderItemType.GIVE);
                orderItem.save();
                //加入 AdminOrder
                AdminOrder adminOrder = AdminOrder.findByOrder(order);
                new AdminOrderItem(orderItem , adminOrder).save();
                specMerchant.stock = specMerchant.stock - 1;
                specMerchant.save();
            }
        }
    }

    /**
     * 订单来源
     */
    public static List<Map<String,Object>> loadOrderSource(long merchantId, String startDate, String endDate){
        String sqlSelect="select count(*) as num,goods_type from orders where fee_merchant_id="+merchantId;

        if(StringUtil.isNotBlank(startDate)){
            sqlSelect += " and DATE_FORMAT(created_at,'%m/%d/%Y') >='"+startDate+"'";
        }
        if(StringUtil.isNotBlank(endDate)){
            sqlSelect += " and DATE_FORMAT(created_at,'%m/%d/%Y') <='"+endDate+"'";
        }

        sqlSelect += " group by goods_type";

        Query query=Order.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    /**
     * 支付类型
     */
    public static List<Map<String,Object>> loadOrderPayType(long merchantId, String startDate, String endDate){
        String sqlSelect="select count(*) as num,payment_type from orders where fee_merchant_id="+merchantId;

        sqlSelect += " and payment_type is not null";

        if(StringUtil.isNotBlank(startDate)){
            sqlSelect += " and DATE_FORMAT(created_at,'%m/%d/%Y') >='"+startDate+"'";
        }
        if(StringUtil.isNotBlank(endDate)){
            sqlSelect += " and DATE_FORMAT(created_at,'%m/%d/%Y') <='"+endDate+"'";
        }

        sqlSelect += " group by payment_type";

        Query query=Order.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    /**
     * 日订单趋势
     */
    public static List<Map<String,Object>> loadOrderTrend(long merchantId, String startDate, String endDate){
        String sqlSelect="select count(*) as num,DATE_FORMAT(created_at,'%Y-%m-%d') days from orders where fee_merchant_id="+merchantId;

        if(StringUtil.isNotBlank(startDate)){
            sqlSelect += " and DATE_FORMAT(created_at,'%m/%d/%Y') >='"+startDate+"'";
        }
        if(StringUtil.isNotBlank(endDate)){
            sqlSelect += " and DATE_FORMAT(created_at,'%m/%d/%Y') <='"+endDate+"'";
        }

        sqlSelect += " group by DATE_FORMAT(created_at,'%Y-%m-%d')";

        Query query=Order.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    /**
     * 查询某一商户下某种状态下的订单列表
     * 订单类型为GoodsType 为PRODUCT类型
     * @param status
     * @param merchantId
     * @return
     */
    public static List<Order> loadByMerchantAndStatus(OrderStatus status , long merchantId,Date beginDate,Date endDate) {
        List<Order> orderList = new ArrayList<>();
        if (status == null || "".equals(status) || "all".equals(status)) {
            orderList = Order.find("deleted = ?1 and merchant.id = ?2   order by createdAt desc", DeletedStatus.UN_DELETED, merchantId).fetch();
        }else {
            orderList = Order.find("deleted = ?1 and status = ?2 and merchant.id = ?3 and createdAt between ?4 and ?5   order by createdAt desc", DeletedStatus.UN_DELETED, status, merchantId,beginDate,endDate).fetch();
        }
        return orderList;
    }


    /**
     * 获取订单的订单产品明细
     * @param orderId
     * @return
     */
    public static List<Map<String , Object>> getOrderItemList(long  orderId){

        String sqlSelect  = "select a.id as item_id, b.id as goods_id, c.id as product_id , c.`name` , c.spec  , c.unit ,a.buy_number , a.sale_price , c.main_image, a.trial_status trialStatus , r.trial trial  " +
                "   from order_items a " +
                "   left join goods b on a.goods_id = b.id " +
                "   left join products c on b.serial_id = c.id " +
                " left join report r on r.order_item_id = a.id  "+
                "   where a.order_id = "+orderId+" and a.deleted = 0" ;
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resulList = query.getResultList();
        return  resulList;
    }


    /**
     * 统计某商户的某用户的订单总量 和订单总金额
     * 订单类型goodsType == 'PRODUCT'
     * 订单状态 status != 'NEW' AND status != 'UNPAID'
     * @return
     */
    public static Map<String , Object> countByWebUserAndMerchant(long merchantId  , long userId , String beganDate , String endDate) {
        String sqlCount = "select  count(a.id) as order_num , sum(ifnull(a.paymented_amount,0)) as total_amount from orders a where a.fee_merchant_id = "+merchantId+" and a.web_user_id = "+userId+" and a.goods_type = 'PRODUCT' and (a.`status` != 'NEW' and a.`status` != 'UNPAID') and a.created_at >= '"+beganDate+"' and a.created_at < '"+endDate+"'";
        Query query = OrderItem.em().createNativeQuery(sqlCount);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resultList = query.getResultList();
        if(resultList != null && resultList.size() > 0){
            return resultList.get(0);
        }
        return null;
    }

    //获取某商户某用户的所有订单
    public static List<Order> loadByMerchantAndUser(long merchantId , long userId){
        return Order.find(" deleted = ?1 and merchant.id = ?2 and webUser.id = ?3 and  goodsType = ?4 and (status!= ?5 and status != ?6 )" , DeletedStatus.UN_DELETED , merchantId , userId , GoodsType.PRODUCT , OrderStatus.NEW , OrderStatus.UNPAID).fetch();
    }

    /**
     * 查询未派送 已支付订单
     * @return
     */
    public static Order orderByIdAndConfirm(long id) {
        return find(" deleted = ?1 and status = ?2 and id = ?3", DeletedStatus.UN_DELETED, OrderStatus.PAID,id).first();
    }

    /**
     * 根据订单派发状态查询
     * @param distributeStatus
     * @return
     */
    public static List<Order> findByDistributeStatus(DistributeStatus distributeStatus,OrderStatus orderStatus , WebUser webUser) {
        if(distributeStatus == DistributeStatus.DISTRIBUTE) {
            return Order.find("deleted = ?1 and status = ?2    and distributeStatus = ?3 order by distributeAt desc" , DeletedStatus.UN_DELETED , orderStatus,distributeStatus).fetch();
        }else{
            if(orderStatus == null ){
                return Order.find("deleted = ?1     and distributeStatus = ?2 and  distributeWebUser.id = ?3 order by distributeAt desc" , DeletedStatus.UN_DELETED ,distributeStatus,webUser.id).fetch();
            }else{
                return Order.find("deleted = ?1 and status = ?2    and distributeStatus = ?3 and  distributeWebUser.id = ?4 order by distributeAt desc" , DeletedStatus.UN_DELETED , orderStatus,distributeStatus,webUser.id).fetch();
            }
        }


    }
    /**
     * 根据订单状态查询订单. 将来肯定需要 增加分页功能
     * @param status
     * @return
     */
    public static List<Order> findByStatusAndWebuserAndMerchantAndDistribute(OrderStatus status,WebUser webUser , DistributeStatus distributeStatus) {
        if(status == null || "".equals(status) || "all".equals(status)){
             if(distributeStatus.equals(DistributeStatus.SEND_DISTRIBUTE) ){
                return find("deleted = ?1 and status = 'DISTRIBUTION' or status = 'DISTRIBUTIONING'   and webUser = ?2  and distributeStatus = ?3   order by createdAt desc" , DeletedStatus.UN_DELETED ,webUser ,DistributeStatus.SEND_DISTRIBUTE).fetch();
            }else{
                 return find(" deleted = ?1 and webUser = ?2  order by createdAt desc",DeletedStatus.UN_DELETED,webUser ).fetch();
             }
        }else {
            if(distributeStatus == null || "".equals(distributeStatus) || "new".equals(distributeStatus) ){
                return find("deleted = ?1 and status = ?2  and webUser = ?3  and distributeStatus != ?4   order by createdAt desc" , DeletedStatus.UN_DELETED , status,webUser,DistributeStatus.ROB_DISTRIBUTE).fetch();
            }else{
                return find("deleted = ?1 and status = ?2  and webUser = ?3  and distributeStatus = ?4 order by createdAt desc" , DeletedStatus.UN_DELETED , status,webUser ,distributeStatus).fetch();
            }


        }
    }
    /**
     * 商户管理查询我的订单
     */
    public static List<Order> findByMerchant(OrderStatus status,WebUser webUser , Merchant merchant,DistributeStatus distributeStatus) {
        if (distributeStatus == null) {
            return find("deleted = ?1 and status = ?2   and merchant.id = ?3  order by createdAt desc", DeletedStatus.UN_DELETED, status, merchant.id).fetch();
        }else {
            return find("deleted = ?1 and status = ?2   and merchant.id = ?3  and distributeStatus = ?4   order by createdAt desc", DeletedStatus.UN_DELETED, status, merchant.id,distributeStatus).fetch();
        }

    }


    public static List<OrderItem> getOrderItemByOrderId(long  orderId){
        String sqlSelect  = "select a.id as item_id, b.id as goods_id, c.id as product_id , c.`name` , c.spec  , c.unit ,a.buy_number , a.sale_price , c.main_image " +
                "   from order_items a " +
                "   left join goods b on a.goods_id = b.id " +
                "   left join products c on b.serial_id = c.id " +
                "   where a.order_id = "+orderId+" and a.deleted = 0" ;
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<OrderItem> resulList = query.getResultList();
        return  resulList;
    }


    public final static String GET_ORDER_ITEMS =
            "select c.`name` , c.spec , c.unit , a.buy_number , a.sale_price , b.id as order_id , a.id as item_id ,  pm.name merchantName  " +
                    "     from order_items a    " +
                    "     left join orders b on a.order_id = b.id   " +
                    "    left join goods c on a.goods_id = c.id   " +
                    "        left join power_merchants pm on pm.id= c.merchant_id  " +
                    "    where a.deleted = 0 and b.deleted = 0  %s ";

    //获取打印数据
    public static List<Order> getPrintDataList(String orderIds){
        String sqlSelect = "" ;
        String sqlWhere = "" ;
        if(StringUtils.isNotBlank(orderIds)){
            orderIds = orderIds.substring(0, orderIds.length()-1);
            sqlWhere = " and a.order_id in ("+orderIds+") ";
        }

        Logger.info("----------getPrintDataList ,获取打印订单Id:%s" , orderIds);
//        Logger.info("----------getPrintDataList ,获取打印订单sqlWhere:%s" , sqlWhere);
        sqlSelect = String.format(GET_ORDER_ITEMS , sqlWhere);
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> itemList =  query.getResultList();

//        Logger.info("----------getPrintDataList ,获取打印订单sqlSelect:%s" , sqlSelect);
        Map<Long , List<Map<String , Object>>> orderItems = new HashMap<>();
        if(itemList != null && itemList.size() > 0){
            for(Map<String , Object> map : itemList){
                    Long order_id = map.get("order_id") != null ?  ConvertUtil.toLong(map.get("order_id")) : null ;
                if (order_id != null && order_id > 0) {

                    if (orderItems.get(order_id) == null) {
                        orderItems.put(order_id, new ArrayList<Map<String, Object>>());
                    }
                    orderItems.get(order_id).add(map);

                }
            }
        }
        List<Order> orderList = Order.find("deleted = 0 and id in ("+ ConvertUtil.escapeSql(orderIds)+")").fetch();

        Double pageSize = 1D;
        if(orderList != null && orderList.size() > 0){
            for(Order order: orderList){
                if(orderItems.get(order.id) != null){
                    int itemLength = orderItems.get(order.id).size();
                   int  printOrderNums = (int)Math.ceil(itemLength/pageSize);
                    order.orderItemPages = new ArrayList<>();
                    for(int i = 0 ; i <printOrderNums ; i++){
                        order.orderItemPages.add(new ArrayList<Map<String, Object>>());
                    }

                    for(int i = 0 ; i < itemLength ; i ++){
                        int innerItemNums = (int)Math.ceil((i+1)/pageSize);

                        order.orderItemPages.get(innerItemNums-1).add(orderItems.get(order.id).get(i));
                    }

                    List<Map<String,Object>> lastOrderItemSplitList = order.orderItemPages.get(printOrderNums-1);
                    if(lastOrderItemSplitList.size() < pageSize){
                        for(int i = lastOrderItemSplitList.size() ; i < pageSize ; i++){
                            lastOrderItemSplitList.add(new HashMap<String, Object>());
                        }
                    }


                }
            }
        }

        return orderList;

    }

    /**
     * 加载所有订单
     *
     * @return
     */
    public static List<Order> loadAllOrder() {
        return Order.find("deleted=?1 ", DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 获取订单的订单产品明细
     */
    public static List<Order> getAllOrderAmount(){
        String sqlSelect  = " select FORMAT(IFNULL(sum(o.amount),0),2) sumAmount from orders o  where o.deleted = 0 " ;
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Order> resulList = query.getResultList();
        return  resulList;
    }


    /**
     * 昨日成交订单数
     * @param beginDate
     * @param endDate
     * @return
     */
    public static List<Order> findYesterdayByOrder(Date beginDate, Date endDate) {
        return Order.find(" deleted = ?1 and  createdAt between ?2 and ?3" , DeletedStatus.UN_DELETED ,beginDate,endDate ).fetch();
    }

    /**
     * 昨日成交金额
     */
    public static List<Order> findYesterdayBySumAcount(String beginDate, String endDate){
        String sqlSelect  = " select FORMAT(IFNULL(sum(o.amount),0),2) sumAmount from orders o  where o.deleted = 0  and o.created_at  between '" + beginDate +"' and '"+endDate +"'";
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Order> resulList = query.getResultList();
        return  resulList;
    }

    /**
     * 昨日成交金额
     */
        public static Order findOrderById(long id) {
            return Order.find("deleted = ?1 and id = ?2 ", DeletedStatus.UN_DELETED,id).first();
        }

    /**
     * 成交额
     */
    public static List<Map<String,Object>> findSumAcountMapByDate(String beginDate, String endDate){
        String sqlSelect  = " select FORMAT(IFNULL(sum(o.amount),0),2) sumAmount from orders o  where o.deleted = 0  and o.created_at  between '" + beginDate +"' and '"+endDate +"'";
        Query query = OrderItem.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resulList = query.getResultList();
        return  resulList;
    }



}
